//
//  ViewController.swift
//  spring
//
//  Created by george on 12/23/15.
//  Copyright © 2015 test. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

	let mover = UIView(frame: .zero)
	var link : CADisplayLink?

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.

		view.addSubview(mover)
		mover.backgroundColor = UIColor.redColor()
	}

	override func viewWillAppear(animated: Bool) {
		super.viewWillAppear(animated)

		let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
		delegate.window?.backgroundColor = UIColor.redColor()

		view.layer.mask = CALayer()
		view.layer.mask?.contents = UIImage(named: "qq")!.CGImage
		view.layer.mask?.position = view.center
	}

	override func viewWillLayoutSubviews() {
		super.viewWillLayoutSubviews()
		mover.frame = CGRectMake(160, 398, 40, 2)
	}

	override func viewDidAppear(animated: Bool) {
		super.viewDidAppear(animated)

		dispatch_after(3, dispatch_get_main_queue()) { () -> Void in

			let scale = CABasicAnimation(keyPath: "bounds")
			scale.fromValue = NSValue(CGRect: CGRectMake(0, 0, 128, 128))
			scale.byValue = NSValue(CGRect: CGRectMake(0, 0, 2000, 2000))
			scale.duration = 2
			scale.removedOnCompletion = true
			scale.delegate = self

			self.view.layer.mask?.addAnimation(scale, forKey: nil)
		}
	}

	override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
		view.layer.mask = nil
	}

	deinit {
		link?.invalidate()
	}

	@IBAction func onBtn(sender: UIButton) {

		link = CADisplayLink(target: self, selector: "onLink")
		link?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
		link?.paused = false
		UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in
			self.mover.frame = CGRectMake(160, 300, 40, 100)
			}, completion: { (finished) -> Void in
				self.link?.paused = true
				self.mover.frame = CGRectMake(160, 398, 40, 2)
		})
	}

	func onLink() {
		print( mover.layer.presentationLayer()?.bounds.size.height )
	}

}

